package com.macro.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.util.IdWorker;
import com.macro.mall.mapper.BasicKeyTextMapper;
import com.macro.mall.mapper.admin.KeyTextMapper;
import com.macro.mall.model.BasicKeyText;
import com.macro.mall.pojo.BasicKeyTextVo;
import com.macro.mall.query.BasicKeyTextQuery;
import com.macro.mall.service.SysKeysService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysKeysServiceImpl implements SysKeysService {

    @Autowired
    private BasicKeyTextMapper basicKeyTextMapper;

    @Autowired
    private KeyTextMapper keyTextMapper;

    @Autowired
    private IdWorker idWorker;

    @Override
    public CommonResult modify(BasicKeyText sysKeyEntDTO) {
        if (StringUtils.isEmpty(sysKeyEntDTO.getId())) {
            sysKeyEntDTO.setId(idWorker.nextId());
            sysKeyEntDTO.setUpdatedDt(new Date());
            sysKeyEntDTO.setCreatedDt(new Date());
            sysKeyEntDTO.setStatus("1");
            if (StringUtils.isEmpty(sysKeyEntDTO.getJudgmentResults())) {
                sysKeyEntDTO.setJudgmentResults("0");
            }
            int row = basicKeyTextMapper.insertSelective(sysKeyEntDTO);
            return result(row, "添加失败");
        }
        sysKeyEntDTO.setUpdatedDt(new Date());
        int row = keyTextMapper.updateByPrimaryKeySelective(sysKeyEntDTO);
        return result(row, "修改失败");
    }

    @Override
    public CommonResult list(BasicKeyTextQuery query) {
        PageHelper.startPage(query.getPage(), query.getPageSize());
        Map<String, Object> result = new HashMap<>();

        List<BasicKeyTextVo> list = basicKeyTextMapper.list(query);
        PageInfo<BasicKeyTextVo> pageInfo = new PageInfo<>(list);
        result.put("total", pageInfo.getTotal());
        result.put("list", pageInfo.getList());
        return CommonResult.success(result);
    }

    @Override
    public CommonResult delete(Long id) {
        int row = basicKeyTextMapper.deleteByPrimaryKey(id);
        return result(row, "删除失败");
    }

    /***
     * 判断修改数据库返回值 返回
     * @param row
     * @param msg
     * @return
     */
    private CommonResult result(int row, String msg) {
        if (row > 0) {
            return CommonResult.success(null);
        }
        return CommonResult.failed(msg);
    }
}
